#include "stm32f10x.h"
#include "hx711.h"
#include "Key.h"
#include "OLED.h"
#include "Delay.h"
#include "hx711.h"
#include "Timer.h"
#include "usart.h"
uint16_t KeyNum;
int value;
int zheng=0,xiao=0;
float weight,reset,pz,save=0;
u8 buff[30];
float Weights=100.0;  //100g
int32_t Weights_100=8493860;  //100g
int main()
{
	Timer_Init();
	SystemInit();
	OLED_Init();
	Key_Init();
	HX711_Init();
	USART1_Config();
	reset = HX711_Get_Data();
		OLED_ShowString(1,1,"zl:000.00g");
		OLED_ShowString(2,1,"je:000.00y");
		OLED_ShowString(3,1,"dj:000.00y/g");
		OLED_ShowString(4,1,"pz:000.00g");
	while(1)
	{
		KeyNum=Key_GetNum();
		value = HX711_Get_Data();
		weight=(float)(value-reset)*Weights/(float)(Weights_100-reset);
		pz=(float)(reset)*Weights/(float)(Weights_100-reset);
		if (Key_Check(KEY_1, KEY_SINGLE) || Key_Check(KEY_1, KEY_REPEAT))//pin5
		{
			xiao ++;
			if(xiao==100)
			{
				xiao=0;
				zheng++;
			}
		}
		if (Key_Check(KEY_2, KEY_SINGLE) || Key_Check(KEY_2, KEY_REPEAT))//pin4
		{
			 xiao --;
			if(xiao==-100)
			{
				xiao=0;
				zheng--;
			}
		}
		if (Key_Check(KEY_3, KEY_SINGLE))//pin7短按
		{	
			save=save+weight*(zheng+xiao*1.0/100);
		}
		if (Key_Check(KEY_3, KEY_LONG))//pin7长按
		{
			zheng = 0;
			xiao=0;
			save=0;
		}
		
		if(KeyNum==1)//pin6
		{
			OLED_Clear();
			OLED_ShowString(2,1,"hj:000.00y");
			OLED_ShowNum(2,4,save,3);
			OLED_ShowNum(2,8,((uint16_t)(save*100))%100,2);
			Delay_s(10000);
			if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_6)==0)
			{
				continue;
			}
		}
		OLED_ShowNum(1,4,weight,3);
		OLED_ShowNum(1,8,((uint16_t)(weight*100))%100,2);
		OLED_ShowNum(2,4,(zheng+xiao*1.0/100)*weight,3);
		OLED_ShowNum(2,8,(((int)((zheng+xiao*1.0/100)*weight)*100))%100,2);
		OLED_ShowNum(3,4,zheng,3);
		OLED_ShowNum(3,8,xiao,2);
		OLED_ShowNum(4,4,pz,3);
		OLED_ShowNum(4,8,((uint16_t)(pz*100))%100,2);
	}

}
void TIM2_IRQHandler(void)
{
	if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
	{
		Key_Tick();
		TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
	}
}
